"""
用户账号相关功能：注册、短信、登录、注销
"""
from django.shortcuts import render, HttpResponse, redirect
from ..forms.account import *
from django.http import JsonResponse
from scripts.generate_code import check_code
import uuid
import datetime


def register(request):
    if request.method == 'GET':
        form = RegisterModelForm
        return render(request, "register.html", {"form": form})
    form = RegisterModelForm(data=request.POST)
    if form.is_valid():
        # 验证通过，写入数据库，密码要是密文
        # instance = form.save()，在数据库新增一条数据，并将新增的这条数据赋值给instance

        # 用户表中新建一条数据
        form.save()
        instance = form.save()

        # 创建交易记录
        price_policy = models.PricePolicy.objects.filter(category=1, title="个人免费版").first()
        models.Transaction.objects.create(
            status=2,
            order=str(uuid.uuid4()),
            user=instance,
            price_policy=price_policy,
            count=0,
            price=0,
            start_datetime=datetime.datetime.now()
        )
        print(form.cleaned_data)
        return JsonResponse({'status': True, 'data': '/login'})
    else:
        print(form.errors)
        return JsonResponse({'status': False, 'errors': form.errors})


def send_sms(request):
    form = SendSmsForm(request, data=request.GET)
    # 只是校验手机号；不能为空、格式是否正确
    if form.is_valid():
        return JsonResponse({"status": True})
    return JsonResponse({"status": False, "errors": form.errors})


def login_sms(request):
    if request.method == "GET":
        form = LoginSmsForm
        return render(request, 'login_sms.html', {"form": form})
    form = LoginSmsForm(data=request.POST)
    if form.is_valid():
        # 用户输入正确，登录成功
        user_object = form.cleaned_data['mobile_phone']
        return JsonResponse({'status': True, 'data': '/index/'})
    return JsonResponse({'status': False, 'error': form.errors})


def login(request):
    if request.method == "GET":
        form = LoginForm(request)
        return render(request, 'login.html', {"form": form})
    form = LoginForm(request, data=request.POST)
    if form.is_valid():
        username = form.cleaned_data['username']
        password = form.cleaned_data['password']
        from django.db.models import Q
        # user_object = models.UserInfo.objects.filter(username=username,password=password).filter()
        user_object = models.UserInfo.objects.filter(Q(email=username) | Q(mobile_phone=username)).filter(
            password=password).first()
        if user_object:
            # 登录成功
            request.session['user_id'] = user_object.id
            request.session.set_expiry(60 * 60 * 24 * 7)
            return redirect('/index/')
        form.add_error('username', '用户名或密码错误')
    return render(request, 'login.html', {'form': form})


def image_code(request):
    """生成图片验证码"""
    from io import BytesIO
    img_object, code = check_code()
    stream = BytesIO()
    img_object.save(stream, "png")
    request.session['code'] = code
    request.session.set_expiry(60)  # 修改session的过期时间
    return HttpResponse(stream.getvalue())


def logout(request):
    request.session.flush()
    return redirect('web:login')
